package com.zues.mvc.controller;

import com.zues.mvc.dao.EmployeeDao;
import com.zues.mvc.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.List;

@Controller
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;

    /**
     * 列表
     */
    @GetMapping("employee")
    public String getList(Model model){
        Collection<Employee> list = employeeDao.getAll();
        model.addAttribute("employeeList",list);
        //测试异常处理器
//        System.out.println(1/0);
        return "employee_list";
    }

    /**
     * 列表
     */
    @RequestMapping(value = "employee/{id}",method = RequestMethod.DELETE)
    public String deleteById(@PathVariable Integer id){
        employeeDao.delete(id);
        return "redirect:/employee";
    }

    /**
     * 详情
     */
    @GetMapping(value = "/employee/{id}")
    public String getEmployeeById(@PathVariable("id") Integer id, Model model){
        Employee employee = employeeDao.get(id);
        model.addAttribute("employee", employee);
        return "employee_update";
    }

    /**
     * 新增
     */
    @PostMapping(value = "/employee")
    public String addEmployee(Employee employee){
        employeeDao.save(employee);
        return "redirect:/employee";
    }

    /**
     * 修改
     */
    @PutMapping(value = "/employee")
    public String updateEmployee(Employee employee){
        employeeDao.save(employee);
        return "redirect:/employee";
    }

    /**
     * 测试@ResponseBody和ajax
     */
    @RequestMapping("/testAjax")
    @ResponseBody
    public Collection<Employee> testResponseUser(){
        return employeeDao.getAll();
    }
}
